import QS from "qs";

export const downloadBlob = (
  url,
  query
): Promise<{ code: number; data?: Blob; message?: string }> => {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open(
      "GET",
      `${import.meta.env.VITE_BASE_API}/${url}?${QS.stringify(query)}`,
      // `${import.meta.env.VITE_BASE_API}/${url}?${QS.stringify(query)}`,
      true
    );
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        var blob = new Blob([this.response], {
          type: "application/pdf;charset=utf-8",
        });
        resolve({
          code: 0,
          data: blob,
        });
        //生成URL
        // let href = window.URL.createObjectURL(blob);

        // if (cb) {
        //   // 有回调，根据type在回调中传入blob对象或url
        //   if (type == "blob") {
        //     cb(blob);
        //   } else {
        //     cb(href);
        //   }
        // } else {
        //   // 无回调，直接导出下载
        //   let link = document.createElement("a");
        //   link.download = "波形.pdf";
        //   link.href = href;
        //   link.click();
        // }
      }
    };
    xhr.onerror = function (e) {
      console.log("download-err", e);
      reject({
        code: 1,
        message: "文件下载失败",
      });
    };
    xhr.send();
  });
};
